<?php 
include_once './socket/Open.php';
include_once './socket/Message.php';
include_once './socket/Base.php';

use socket\Open;
use socket\Message;
use socket\Base;

class Index extends Base
{
	/**
	 * IP
	 * @var string
	 */
	private $host;
	
	/**
	 * 端口号
	 * @var int
	 */
	private $post;
	
	/**
	 * websocket对象
	 * @var Object
	 */
	private $serve;
	
	
	public function __construct($host,$post)
	{
		parent::__construct();
		$this->host = $host;
		$this->post = $post;
		$this->serve = new swoole_websocket_server($this->host,$this->post);
		$this->serve->set([
				'worker_num' =>  1,
				'daemonize' => true,
				'task_worker_num' => 200
		]);
		$this->serve->on('start',[$this,'onStart']);
		$this->serve->on('open',[$this,'onOpen']);
		$this->serve->on('task',[$this,'onTask']);
		$this->serve->on('finish',[$this,'onFinish']);
		$this->serve->on('message',[$this,'onMessage']);
		$this->serve->on('close',[$this,'onClose']);
		$this->serve->start();
	}
	
	public function onStart()
	{
		
		$this->redis-> set('user_list',json_encode([]));
	}
	
	public function onFinish($server,$request)
	{
		echo 2;
	}
	public function onTask($server,$request,$data)
	{
	}
	/**
	 * 客户端连接成功时间
	 * @param object $server
	 * @param object $request
	 */
	public function onOpen($server,$request)
	{
		$open = new Open($server,$request);
		$open->setInter();
	}
	
	/**
	 * 客户端发送消息事件
	 * @param object $server
	 * @param object $request
	 */
	public function onMessage($server,$request)
	{
		$message = new Message($server,$request);
	}
	
	/**
	 * 客户端关闭事件
	 * @param object $server
	 * @param object $request
	 */
	public function onClose($server,$request)
	{
		//客户端关闭，清理退出的用户
		$user_list = json_decode($this->redis->get('user_list'),true);
		
		foreach ($user_list as $k => $v) {
			if($v['fd'] == $request)unset($user_list[$k]);
		}
		//遍历数组给对象发送消息
		foreach ($user_list as $val) {
			$list = [
					'code' => 2,
					'user_list' => $user_list
			];
			$this->serve -> push($val['fd'],json_encode($list));
		}
		$this->redis->set('user_list',json_encode($user_list));
	}
}

$index= new Index('0.0.0.0',5024);